<template>
  <div id="app">
    <router-view/>
    <theme-picker/>
  </div>
</template>

<script>
import ThemePicker from "@/components/ThemePicker";
import {closeSocket, initWebSocket, isWebSocketConnected, sendMsg} from '@/utils/websocket'
import {getToken} from '@/utils/auth'

export default {
  name: "App",
  components: {ThemePicker},
  metaInfo() {
    return {
      title: this.$store.state.settings.dynamicTitle && this.$store.state.settings.title,
      titleTemplate: title => {
        return title ? `${title} - ${process.env.VUE_APP_TITLE}` : process.env.VUE_APP_TITLE
      }
    }
  },
  mounted() {
    console.log("App mounted!")
    if (getToken()) {
      console.log("用户已登录")
      if (isWebSocketConnected()) {
        console.log("websocket已连接")
      } else {
        let token = getToken();
        if (!token || token === "") return;

        console.log("websocket未连接，准备重连！")
        let websocketUrl = process.env.VUE_APP_WEB_SOCKET + '?token=' + token;
        initWebSocket(websocketUrl);
      }
    } else {
      console.log("用户未登录")
      if (isWebSocketConnected()) {
        console.log("websocket依然处于连接状态，准备将其关闭！")
        closeSocket(1444, "用户未登录，客户端主动关闭websocket连接!")
      }
    }

    this.init();
  },
  destroyed() {
    document.removeEventListener("visibilitychange", e => {
      console.log("document的visibilitychange监听事件被移除.")
    })

    window.removeEventListener("beforeunload", e => {
      console.log("window的beforeunload监听事件被移除.")
    })
  },
  methods: {
    init() {
      /*浏览器标签页切换会触发"visibilitychange"事件*/
      document.addEventListener("visibilitychange", e => {
        //如下代码实测有效
        // if (document.visibilityState === "hidden") {
        //   console.log("app页面被切换走了")
        // } else {
        //   console.log("app页面被切换回来了")
        // }
      })

      //浏览器关闭、标签页关闭或刷新时均会触发"beforeunload"事件
      window.addEventListener('beforeunload', e => {
        console.log("页面被刷新或关闭了！ e= ", e)
        closeSocket(1000, '页面被刷新或关闭了,客户端主动关闭websocket.');
      })

      // window.upload = function (event) {
      //
      // }
    }
  }
};
</script>
<style>
#app .theme-picker {
  display: none;
}

</style>
